import random

from django.http import HttpResponse
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from meiduo_mall.libs.captcha.captcha import captcha
from celery_tasks.sms import tasks as sms_tasks
from . import constants
from . import serializers
from meiduo_mall.libs.yuntongxun import sms

#  图形验证码   /image_codes/(?P<image_code_id>[\w-]+)/
class ImageCodeView(APIView):
    '''生成图片验证码'''
    def get(self, request, image_code_id):
        '''
        创建图片验证码
        接受参数, 路由传参
        校验参数, 路由中正则已经校验
        业务处理,
                生成图片验证码, 和图片本身,
                数据库缓存图片内容(UUId:text)
        返回结果,
                返回前端图片,
        '''

        text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        return HttpResponse(image, content_type='image/jpg')


#短信验证码GET /sms_codes/(?P<mobile>1[3-9]\d{9})/?image_code_id=xxx&text=xxx
class SmsCodesView(GenericAPIView):
    '''短信验证码'''
    serializer_class = serializers.ImageCodeCheckSerializers
    def get(self, request, mobile):
        '''
        创建短信验证码
        序列化器校验参数
        业务处理
        返回结果
        '''
        # 判断图形验证码
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        redis_conn = get_redis_connection('verify_code')
        # 调用redis数据库一次存多值优化
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 存send_flag_, 防止用户多次访问
        pl.setex('send_flag_%s'% mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()
        #短信验证码发送
        # sms.CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES//60], 1)
        #

        sms_code_expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
        sms_tasks.send_sms_code.delay(mobile, sms_code, sms_code_expires)

        return Response({'message': 'OK'})





















































